package com.pxl.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pxl.springbootinit.mapper.UserMapper;
import com.pxl.springbootinit.model.dto.user.CustomUserDetails;
import com.pxl.springbootinit.model.entity.User;
import com.pxl.springbootinit.model.enums.AvailableStatusEnum;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userAccount) throws UsernameNotFoundException {
        System.out.println("loadUserByUsername :" + userAccount);
        //查询用户
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_account", userAccount);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        return new CustomUserDetails(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                user.getRole(),
                user.getStatus().equals(AvailableStatusEnum.ACTIVE.getValue()));
    }
}
